import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:fluwx_no_pay/fluwx_no_pay.dart' as fluwx;

class BusinessCustomerDetailsServiceSmsTab extends StatefulWidget {
  BusinessCustomerDetailsServiceSmsTab({
    Key key,
    @required this.vipId,
    @required this.speakTypeId,
    @required this.inputApi,
    this.phoneNumber,
    this.sms = true,
    this.privateWx = true,
    this.enterpriseWx = false,
    this.noTemplate = false,
  }) : super(key: key);

  final bool noTemplate;

  final String vipId;

  final String speakTypeId;

  final String inputApi;

  //手机号码
  final String phoneNumber;

  //短信
  final bool sms;

  //微信
  final bool privateWx;

  //企业微信
  final bool enterpriseWx;

  @override
  _BusinessCustomerDetailsServiceSmsTabState createState() => _BusinessCustomerDetailsServiceSmsTabState();
}

class _BusinessCustomerDetailsServiceSmsTabState extends State<BusinessCustomerDetailsServiceSmsTab> with AutomaticKeepAliveClientMixin {
  TextEditingController _controller = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (widget.noTemplate) return buildNoTemplate();
    return Column(
      children: [
        Expanded(
          child: BaseRefreshComponent(
            path: '/vip/speakart/page/query',
            params: {'speakTypeId': widget.speakTypeId},
            buildItem: _buildListItem,
            controller: new BaseRefreshController(),
          ),
        ),
        _buildFooterWidget(),
      ],
    );
  }

  Widget buildNoTemplate() {
    return Column(
      children: [
        Expanded(child: SizedBox()),
        _buildFooterWidget(),
      ],
    );
  }

  Widget _buildListItem(Map<String, dynamic> item, int index) {
    String depict = BaseUtils.getKeyData(item, 'depict').toString();
    String speakArtTypeName = BaseUtils.getKeyData(item, 'speakArtTypeName').toString();
    return BaseCardComponent(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(depict),
          SizedBox(height: 12.0),
          Row(
            children: [
              SizedBox(width: 4),
              Icon(BaseIconData.x3Label, size: 14),
              SizedBox(width: 4),
              Text(
                speakArtTypeName,
                style: Theme.of(context).textTheme.subtitle2,
              ),
              Expanded(child: SizedBox()),
              _buildBaseButton(() => _controller.text = depict),
            ],
          )
        ],
      ),
    );
  }

  Widget _buildBaseButton(Function() onPress) {
    Color primaryColor = Theme.of(context).primaryColor == Colors.white ? BaseBodyTheme.textColor : Theme.of(context).primaryColor;
    Color borderColor = Theme.of(context).primaryColor == Colors.white ? Color(0xFFF3F3F3) : Theme.of(context).primaryColor;
    return InkWell(
      onTap: onPress,
      child: Container(
        width: 64.0,
        height: 28.0,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(3),
          border: Border.all(color: borderColor),
        ),
        child: Text('选择', style: TextStyle(fontSize: BaseButtonTheme.buttonTextSize, color: primaryColor)),
      ),
    );
  }

  Widget _buildFooterWidget() {
    return Container(
      padding: EdgeInsets.all(12.0),
      color: Colors.white,
      child: Column(
        children: [
          _buildTextFieldWidget(),
          SizedBox(height: 8.0),
          _buildFooterButtonWidget(),
        ],
      ),
    );
  }

  Widget _buildTextFieldWidget() {
    return TextField(
      controller: _controller,
      maxLines: 6,
      style: Theme.of(context).textTheme.bodyText2,
      decoration: InputDecoration(
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Theme.of(context).scaffoldBackgroundColor),
        ),
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Theme.of(context).scaffoldBackgroundColor),
        ),
      ),
    );
  }

  Widget _buildFooterButtonWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        if (widget.sms) Expanded(child: _buildFooterButtonItemWidget(BaseAssets.sms, '发短信', Theme.of(context).textTheme.bodyText2.color, _sendSms)),
        if (widget.sms) SizedBox(width: 8),
        if (widget.privateWx) Expanded(child: _buildFooterButtonItemWidget(BaseAssets.privateWx, '发微信', Color(0XFF02BB29), _sendSeWeChat)),
        if (widget.enterpriseWx) SizedBox(width: 8),
        if (widget.enterpriseWx) Expanded(child: _buildFooterButtonItemWidget(BaseAssets.enterpriseWx, '发企微', Color(0XFF0079DE), _sendWXWork)),
      ],
    );
  }

  Widget _buildFooterButtonItemWidget(String imageUrl, String text, Color color, Function() onPressed) {
    TextStyle textStyle = Theme.of(context).textTheme.bodyText2.copyWith(color: color);
    return BaseOutLineButton(onPressed: onPressed, primaryColor: textStyle.color, child: Row(mainAxisSize: MainAxisSize.min, children: [Image.asset(imageUrl), SizedBox(width: 8), Text(text, style: textStyle)]));
  }

  ///发短信
  void _sendSms() {
    if (_controller.text.isNotEmpty) {
      BaseComponentUtils.showLoadingDialog(context);
      dioUtil.fetch('/vip/customer/server/tool/sendsms', params: {'vipId': widget.vipId, "message": _controller.text}).then((BaseHttpResultModel result) {
        BaseComponentUtils.hideLoadingDialog(context);
        if (result.success == true) {
          BaseRouterUtil().pop();
          BaseClipboardTool.setDataToastMsg(_controller.text, toastMsg: '发生内容已经复制到粘贴板，请粘贴发送');
          BaseUrlLauncherUtil.sms(widget.phoneNumber);
        }
      });
    } else {
      BaseUtils.showToast('请选择或者输入需要发送的内容');
    }
  }

  ///发微信
  void _sendSeWeChat() {
    if (_controller.text.isNotEmpty) {
      BaseComponentUtils.showLoadingDialog(context);
      dioUtil.fetch('/vip/customer/server/tool/sendwechat', params: {'vipId': widget.vipId, "message": _controller.text, 'sendType': '0'}).then((BaseHttpResultModel result) {
        BaseComponentUtils.hideLoadingDialog(context);
        if (result.success == true) {
          _shareText(_controller.text);
        }
      });
    } else {
      BaseUtils.showToast('请选择或者输入需要发送的内容');
    }
  }

  /// 打开企业微信
  void _sendWXWork() {
    if (_controller.text.isNotEmpty) {
      BaseComponentUtils.showLoadingDialog(context);
      dioUtil.fetch('/vip/customer/server/tool/sendwechat', params: {'vipId': widget.vipId, "message": _controller.text, 'sendType': '1'}).then((BaseHttpResultModel result) {
        BaseComponentUtils.hideLoadingDialog(context);
        if (result.success == true) {
          BaseRouterUtil().pop();
          BaseClipboardTool.setDataToastMsg(_controller.text, toastMsg: '发生内容已经复制到粘贴板，请粘贴发送');
          BaseUrlLauncherUtil.url('wxwork://');
        }
      });
    } else {
      BaseUtils.showToast('请选择或者输入需要发送的内容');
    }
  }

  ///分享文本操作
  void _shareText(String text) async {
    bool isWeChatInstalled = await fluwx.isWeChatInstalled;
    if (!isWeChatInstalled) {
      BaseUtils.showToast("您还没安装微信");
    } else {
      BaseRouterUtil().pop();
      fluwx.shareToWeChat(fluwx.WeChatShareTextModel(text));
    }
  }

  @override
  bool get wantKeepAlive => true;
}
